package dingo

import (
	"errors"
	"github.com/dgrijalva/jwt-go"
	"time"
)

var (
	jwtSecret []byte = []byte("Secret-yundian") // 加密码串
	jwtExpire int    = 24                       // 24小时
	jwtIssure string = "yundian"                // 签名发行者
)

// 自定义 Claims
type CustomClaims struct {
	UserId       int
	UserName     string
	IsAdmin      uint8
	IsPlace      uint8
	IsDraw       uint8
	ParentId     int
	TimeStamp    int64
	Platform     string
	MessageTypes string
	jwt.StandardClaims
}

//func NewCustomClaims(userId int, userName string, isAdmin bool) *CustomClaims {
//	return &CustomClaims{
//		UserId: userId,
//		UserName: userName,
//		IsAdmin: isAdmin,
//		StandardClaims: jwt.StandardClaims{
//			//ExpiresAt: time.Now().Unix() + 60*60*24*7, // 过期时间 7天
//			//ExpiresAt: time.Now().Unix() + global.Cfg.Auth.JwtExpire,
//			ExpiresAt: time.Now().Add(time.Duration(jwtExpire) * time.Hour).Unix(),
//			Issuer:    jwtIssure, // 签名的发行者
//		},
//	}
//}

// 生成 Token
func GenerateTokenApp(userId int, userName string, parentId int, messageTypes string) (string, error) {
	claims := &CustomClaims{
		UserId:       userId,
		UserName:     userName,
		ParentId:     parentId,
		MessageTypes: messageTypes,
		//TimeStamp: time.Now().Unix(), // 加了会出现token错误
		StandardClaims: jwt.StandardClaims{
			//ExpiresAt: time.Now().Unix() + 60*60*24*7, // 过期时间 7天
			//ExpiresAt: time.Now().Unix() + global.Cfg.Auth.JwtExpire,
			ExpiresAt: time.Now().Add(time.Duration(jwtExpire) * time.Hour).Unix(),
			Issuer:    jwtIssure, // 签名的发行者
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString(jwtSecret)
}

// 生成 Token
func GenerateToken(userId int, userName string, isAdmin uint8, parentId int, isPlace, IsDraw uint8, platform string) (string, error) {
	claims := &CustomClaims{
		UserId:   userId,
		UserName: userName,
		IsAdmin:  isAdmin,
		ParentId: parentId,
		IsPlace:  isPlace,
		IsDraw:   IsDraw,
		Platform: platform,
		//TimeStamp: time.Now().Unix(), // 加了会出现token错误
		StandardClaims: jwt.StandardClaims{
			//ExpiresAt: time.Now().Unix() + 60*60*24*7, // 过期时间 7天
			//ExpiresAt: time.Now().Unix() + global.Cfg.Auth.JwtExpire,
			ExpiresAt: time.Now().Add(time.Duration(jwtExpire) * time.Hour).Unix(),
			Issuer:    jwtIssure, // 签名的发行者
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString(jwtSecret)
}

// 解析 Token
func ParseToken(tokenString string) (*CustomClaims, error) {
	customClaims := new(CustomClaims)
	token, err := jwt.ParseWithClaims(tokenString, customClaims, func(token *jwt.Token) (i interface{}, err error) {
		return jwtSecret, nil
	})
	if err != nil {
		return nil, err
	}
	// token 校验成功
	if token.Valid {
		return customClaims, nil
	}
	return nil, errors.New("Token解析失败,无效的Token")
}
